package cn.itcast.bos.service.take_delivery.impl;

import java.util.Date;
import java.util.Set;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.dao.base.FixedAreaRepository;
import cn.itcast.bos.dao.take_delivery.OrderRepository;
import cn.itcast.bos.dao.take_delivery.WorkBillRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.constant.Constants;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.take_delivery.OrderService;
import cn.itcast.bos.utils.UUIDUtils;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private AreaRepository areaRepository;
	@Autowired
	private FixedAreaRepository fixedAreaRepository;
	@Autowired
	private WorkBillRepository workBillRepository;
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	@Override
	public void saveOrder(Order order) {
		// 设置订单id
		order.setOrderNum(UUIDUtils.getUUID());
		// 设置订单状态
		order.setStatus("1");
		// 设置下单时间
		order.setOrderTime(new Date());
		// 查询出持久态的寄件人区域
		Area sendArea = order.getSendArea();
		Area persistSendArea = areaRepository.findByProvinceAndCityAndDistrict(sendArea.getProvince(),
				sendArea.getCity(), sendArea.getDistrict());
		order.setSendArea(persistSendArea);
		// 查询出持久态的收件人区域
		Area recArea = order.getRecArea();
		Area persistRecArea = areaRepository.findByProvinceAndCityAndDistrict(recArea.getProvince(), recArea.getCity(),
				recArea.getDistrict());
		order.setRecArea(persistRecArea);

		// 自动分单1：寄件地址完全匹配用户的地址,来找到对用的fixedId,从而找到对应的快递员,来完成分单
		// 根据寄件地址匹配用户地址找到fixedId
		String fixedAreaId = WebClient.create(Constants.CRM_MANAGEMENT_URL
				+ "/services/customerService/findFixedAreaIdBySendAddress?sendAddress=" + order.getSendAddress())
				.accept(MediaType.APPLICATION_JSON).get(String.class);
		if (fixedAreaId != null) {
			// 通过定区id找到定区
			FixedArea fixedArea = fixedAreaRepository.findOne(fixedAreaId);
			// 通过定区找到定区关联的快递员
			Set<Courier> couriers = fixedArea.getCouriers();
			if (couriers.size() != 0) {
				Courier courier = couriers.iterator().next();
				// 将订单关联快递员,设置分单的状态,并且保存订单
				saveOrder(order, courier);
				// 生成工单,并通知快递员
				generateWorkBill(order);
				System.out.println("自动分单1成功！！！！");
				return;
			}
		}

		// 自动分单2：寄件地址不匹配用户地址, 根据寄件地址包含分区关键字,找到分区从而匹配相应的定区
		Set<SubArea> subareas = persistSendArea.getSubareas();
		for (SubArea subArea : subareas) {
			if (order.getSendAddress().contains(subArea.getAssistKeyWords())
					|| order.getSendAddress().contains(subArea.getKeyWords())) {
				// 通过分区找到定区找到对应的快递员
				Set<Courier> couriers = subArea.getFixedArea().getCouriers();
				if (couriers.size() != 0) {
					Courier courier = couriers.iterator().next();
					// 将订单关联快递员,设置分单的状态,并且保存订单
					saveOrder(order, courier);
					// 生成工单,并通知快递员
					generateWorkBill(order);
					System.out.println("自动分单2成功！！！！");
					return;
				}
			}
		}

		// 人工分单
		// 设置分单的类型为自动分单
		order.setOrderType("2");
		orderRepository.save(order);
		System.out.println("人工分单成功！！！！");
	}

	// 将订单关联快递员,设置分单的状态,并且保存订单
	private void saveOrder(Order order, Courier courier) {
		// 将订单关联快递员
		order.setCourier(courier);
		// 设置分单的类型为自动分单
		order.setOrderType("1");
		// 保存订单
		orderRepository.save(order);
	}

	// 生成工单 , 发送短信
	private void generateWorkBill(final Order order) {
		// 生成工单
		WorkBill workBill = new WorkBill();
		workBill.setType("新");
		workBill.setPickstate("未通知快递员");
		workBill.setBuildtime(new Date());
		workBill.setAttachbilltimes(0);
		workBill.setRemark(order.getRemark());
		String smsNumber = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(smsNumber);
		workBill.setCourier(order.getCourier());
		workBill.setOrder(order);
		// 保存工单
		workBillRepository.save(workBill);

		// activeMQ 发送短信
		final String content = "短信序号：" + smsNumber + ",取件地址：" + order.getSendAddress() + ",联系人:" + order.getSendName()
				+ ",手机号:" + order.getSendMobile() + "，快递员捎话：" + order.getSendMobileMsg();
		jmsTemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				// 定义消息的格式
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier().getTelephone());
				mapMessage.setString("content", content);
				return mapMessage;
			}
		});
		// 更新工单状态
		workBill.setPickstate("已通知快递员");
	}

	@Override
	public Order findByOrderNum(String orderNum) {
		return orderRepository.findByOrderNum(orderNum);
	}

}
